package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * @author DongYu Zhou
 * @date 2022/6/29 22:18
 */
@Api(tags = "短信服务接口")
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送短信验证码")
    @GetMapping("/send/{phone}")
    public R send(@PathVariable("phone") String phone) {
        // 查看是否已经发送验证码
        String s = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(s)) {
            return R.ok();
        }
        //获取一个四位的验证码
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        //调用service发送
        Boolean b = msmService.send(phone,map);
        if (b) {
            // 发送成功 存入redis 1分钟
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送失败");
        }

    }
}
